<template>
  <div class="product-detail-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar 
      title="商品详情" 
      left-arrow 
      @click-left="$router.back()"
      fixed
      z-index="99"
      text-color="#fff"
    >
      <template #right>
        <van-icon name="share-o" color="#fff" size="18" class="nav-icon" />
        <van-icon 
          :name="isFavorite ? 'star' : 'star-o'" 
          :color="isFavorite ? '#ffd700' : '#fff'" 
          size="18" 
          class="nav-icon" 
          @click="addToFavorites" 
        />
      </template>
    </van-nav-bar>

    <!-- 商品图片轮播 -->
    <van-swipe class="image-swipe" :loop="true" :autoplay="3000">
      <van-swipe-item v-for="(img, index) in [product.img || product.pic]" :key="index">
        <van-image 
          :src="img" 
          fit="cover" 
          class="detail-image"
        />
      </van-swipe-item>
    </van-swipe>

    <!-- 商品信息区域 -->
    <div class="product-info-wrapper">
      <!-- 商品标题和价格 -->
      <div class="price-section">
        <div class="current-price">¥{{ product.price }}</div>
        <div class="original-price" v-if="product.originalPrice">¥{{ product.originalPrice }}</div>
        <van-tag v-if="product.discount" class="discount-tag" type="danger">{{ product.discount }}</van-tag>
      </div>

      <!-- 商品标题 -->
      <div class="product-title">{{ product.title }}</div>

      <!-- 作者信息 -->
      <div class="product-author">作者: {{ product.author || '匿名作者' }}</div>

      <!-- 销量 -->
      <div class="sales-info">
        <span>已售 {{ product.soldCount || product.count || 0 }}</span>
      </div>

      <!-- 商品属性 -->
      <van-cell-group class="attr-group">
        <van-cell title="书籍编号" :value="product.id" />
        <van-cell title="成色" :value="product.condition" />
      </van-cell-group>

      <!-- 分割线 -->
      <van-divider content="商品详情" />

      <!-- 商品详情描述 -->
      <div class="detail-desc">
        <van-image 
          :src="product.img || product.pic" 
          fit="contain" 
          class="detail-pic"
        />
        <p class="desc-text">{{ product.description}} </p>
      </div>
    </div>

    <!-- 底部操作栏（含数量选择和加入购物车） -->
    <div class="bottom-bar">
      <!-- 收藏按钮 -->
      <div class="bar-item" @click="addToFavorites">
        <van-icon 
          :name="isFavorite ? 'star' : 'star-o'" 
          :color="isFavorite ? '#ffd700' : '#666'" 
          size="20"
        />
      </div>
      
      <!-- 客服按钮 -->
      <div class="bar-item" @click="showContact">
        <van-icon name="chat-o" />
        <span>客服</span>
      </div>
      
      <!-- 数量选择区域 -->
      <div class="quantity-selector">
        <button class="quantity-btn" @click="decreaseCount">-</button>
        <span class="quantity-value">{{ count }}</span>
        <button class="quantity-btn" @click="increaseCount">+</button>
      </div>
      
      <!-- 加入购物车按钮 -->
      <van-button class="add-cart-btn" type="primary" @click="confirmAddCart">
        加入购物车
      </van-button>
    </div>
  </div>
</template>

<script>
import { showToast, Dialog } from 'vant';
import { getProductDetailByIdAPI } from "@/api/product.js";
import dayjs from 'dayjs'
import { addCartAPI } from "@/api/cart.js";
import { getMyFavorites, addFavorite, deleteFavorite } from "@/api/favorite.js";

export default {
  data() {
    return {
      product: {},
      count: 1,          // 购买数量
      maxCount: 10,      // 最大购买数量限制
      productId: null,
      isFavorite: false, // 收藏状态
      favoriteId: null   // 当前收藏记录ID
    };
  },
  mounted() {
    this.loadData();
  },
  methods: {
    loadData() {
      this.productId = this.$route.query.id || this.$route.query.productId;
      
      if (!this.productId) {
        showToast('未找到商品ID');
        return;
      }

      getProductDetailByIdAPI(this.productId).then(result => {
        this.product = result.data;
        // 可根据接口返回的库存设置最大购买数量
        if (this.product.stock) {
          this.maxCount = this.product.stock;
        }
        // 检查是否已收藏
        this.checkIfFavorite();
      }).catch(error => {
        showToast(error.message || '获取商品详情失败');
      });
    },
    
    // 减少数量
    decreaseCount() {
      if (this.count > 1) {
        this.count--;
      } else {
        showToast('最少购买1件');
      }
    },
    
    // 增加数量
    increaseCount() {
      if (this.count < this.maxCount) {
        this.count++;
      } else {
        showToast(`最多购买${this.maxCount}件`);
      }
    },
    
    // 确认加入购物车
    confirmAddCart() {
      let params = {
        product_id: this.productId,
        count: this.count,
      };
      
      addCartAPI(params).then(result => {
        showToast(result.msg || '加入购物车成功');
      }).catch(() => {
        showToast('加入购物车失败');
      });
    },
    
    // 检查是否已收藏
    async checkIfFavorite() {
      if (!this.product?.id) return;
      try {
        const { data } = await getMyFavorites();
        const match = (data || []).find(item => item.productId === this.product.id);
        this.isFavorite = !!match;
        this.favoriteId = match ? match.id : null;
      } catch (error) {
        console.error('检查收藏状态失败', error);
      }
    },
    
    // 收藏/取消收藏
    async addToFavorites() {
      if (!this.product?.id) {
        showToast('商品信息未加载完成');
        return;
      }
      
      if (this.isFavorite && this.favoriteId) {
        try {
          await deleteFavorite(this.favoriteId);
          this.isFavorite = false;
          this.favoriteId = null;
          showToast('已取消收藏');
        } catch (error) {
          showToast(error?.message || '取消收藏失败');
        }
        return;
      }

      const payload = {
        productId: this.product.id,
        pic: this.product.pic || this.product.img,
        title: this.product.title,
        author: this.product.author,
        price: this.product.price,
        originalPrice: this.product.originalPrice
      };

      try {
        const { data } = await addFavorite(payload);
        this.isFavorite = true;
        this.favoriteId = data?.id || null;
        showToast('收藏成功');
      } catch (error) {
        showToast(error?.message || '收藏失败');
      }
    },
    
    // 联系客服
    showContact() {
      Dialog.alert({
        title: '联系客服',
        message: '客服工作时间: 9:00-21:00'
      });
    }
  }
};
</script>

<style scoped lang="less">
.product-detail-page {
  padding-bottom: 55px;
  background-color: #f9f5ed; /* 改为与列表页一致的浅棕色背景 */
  min-height: 100vh;
}

// 图片轮播
.image-swipe {
  width: 100%;
  height: 300px;
  background-color: #fff;
  
  .detail-image {
    width: 100%;
    height: 100%;
  }
}

// 导航栏样式
.nav-icon {
  margin-left: 15px;
}

// 商品信息区域
.product-info-wrapper {
  padding: 15px;
  background-color: #fff;
  margin-bottom: 10px;
  
  .price-section {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    
    .current-price {
      font-size: 24px;
      color: #8b4513; /* 改为主题棕色 */
      font-weight: bold;
    }
    
    .original-price {
      font-size: 14px;
      color: #999;
      text-decoration: line-through;
      margin-left: 10px;
    }
    
    .discount-tag {
      margin-left: 10px;
      background-color: #f5e8d0; /* 浅棕色标签背景 */
      color: #8b4513; /* 棕色标签文字 */
      border-color: #8b4513;
    }
  }
  
  .product-title {
    font-size: 16px;
    line-height: 1.5;
    margin-bottom: 8px;
    color: #333;
  }
  
  .product-author {
    font-size: 14px;
    color: #666;
    margin-bottom: 10px;
  }
  
  .sales-info {
    font-size: 12px;
    color: #8b4513; /* 改为主题棕色 */
    padding: 10px 0;
    border-bottom: 1px solid #f5e8d0; /* 浅棕色分隔线 */
  }
  
  .attr-group {
    margin-top: 10px;
    
    /deep/ .van-cell {
      border-bottom: 1px solid #f5e8d0; /* 浅棕色分隔线 */
      padding: 12px 0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .van-cell__title {
        color: #8b4513; /* 改为主题棕色 */
        width: 80px;
      }
      
      .van-cell__value {
        color: #333;
      }
    }
  }
  
  .detail-desc {
    padding: 15px 0;
    
    .detail-pic {
      width: 100%;
      margin-bottom: 15px;
    }
    
    .desc-text {
      color: #666;
      line-height: 1.6;
      font-size: 14px;
    }
  }
}

// 底部操作栏
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 55px;
  display: flex;
  align-items: center;
  background-color: #fff;
  border-top: 1px solid #f5e8d0; /* 浅棕色分隔线 */
  padding: 0 10px;
  
  .bar-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    color: #8b4513; /* 改为主题棕色 */
    
    .van-icon {
      font-size: 20px;
      margin-bottom: 3px;
    }
    
    &:first-child {
      span {
        display: none; // 隐藏收藏按钮文字
      }
    }
  }
  
  // 数量选择器样式
  .quantity-selector {
    flex: 2;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 40px;
    
    .quantity-btn {
      width: 30px;
      height: 30px;
      border: 1px solid #f5e8d0; /* 浅棕色边框 */
      background: #fff;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 16px;
      cursor: pointer;
      outline: none;
      color: #8b4513; /* 改为主题棕色 */
    }
    
    .quantity-value {
      width: 40px;
      text-align: center;
      font-size: 16px;
      color: #333;
    }
  }
  
  // 加入购物车按钮
  .add-cart-btn {
    flex: 3;
    height: 40px;
    margin-left: 10px;
    border-radius: 20px;
    font-size: 14px;
    background-color: #8b4513; /* 主题棕色按钮 */
    border-color: #8b4513;
    
    &:active {
      background-color: #6d3810; /* 深色版本用于点击状态 */
      border-color: #6d3810;
    }
  }
}
</style>